package com.walkline.screen;

import java.util.Vector;

import net.rim.device.api.system.ApplicationDescriptor;
import net.rim.device.api.system.Characters;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.FontFamily;
import net.rim.device.api.ui.FontManager;
import net.rim.device.api.ui.Ui;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.AutoTextEditField;
import net.rim.device.api.ui.container.MainScreen;

import com.walkline.app.MusicAppConfig;
import com.walkline.music.MusicPlayer;
import com.walkline.music.MusicSDK;
import com.walkline.music.inf.Song;
import com.walkline.music.inf.SongDetails;
import com.walkline.music.inf.SongsList;
import com.walkline.util.Enumerations.RefreshActions;
import com.walkline.util.Enumerations.Toplists;
import com.walkline.util.Function;
import com.walkline.util.ui.ForegroundManager;
import com.walkline.util.ui.ListStyleButtonField;
import com.walkline.util.ui.ListStyleButtonSet;

public final class MusicScreen extends MainScreen
{
	ForegroundManager _foreground = new ForegroundManager(0);
	ListStyleButtonSet _toplistSet = new ListStyleButtonSet();
	ListStyleButtonSet _listSet = new ListStyleButtonSet();
	ListStyleButtonSet _searchSet = new ListStyleButtonSet();
	ListStyleButtonField _item;
	MusicSDK _music = MusicSDK.getInstance();
	AutoTextEditField _editSearch;
	MusicPlayer _player = new MusicPlayer();

    public MusicScreen()
    {
    	super (NO_VERTICAL_SCROLL | USE_ALL_HEIGHT | NO_SYSTEM_MENU_ITEMS);

    	String appVer = "v" + ApplicationDescriptor.currentApplicationDescriptor().getVersion();
        setTitle(MusicAppConfig.APP_TITLE + " - " + appVer);

		try {
			FontFamily family = FontFamily.forName("BBGlobal Sans");
			Font appFont = family.getFont(Font.PLAIN, 8, Ui.UNITS_pt);
			FontManager.getInstance().setApplicationFont(appFont);
		} catch (ClassNotFoundException e) {}

        _editSearch = new AutoTextEditField("Search: ", "", 20, AutoTextEditField.NO_NEWLINE | AutoTextEditField.NON_SPELLCHECKABLE)
        {
        	protected boolean keyChar(char key, int status, int time)
        	{
            	switch (key)
            	{
        			case Characters.ENTER:
        				if (_editSearch.getText().trim().equals(""))
        				{
        					_editSearch.setFocus();
        				} else {
        					searchSongs(_editSearch.getText());	
        				}

        	            return true;
                }

        		return super.keyChar(key, status, time);
        	}
        };

        add(_editSearch);

        _item = new ListStyleButtonField("热歌榜");
        _item.setChangeListener(new FieldChangeListener()
        {
			public void fieldChanged(Field field, int context)
			{
				UiApplication.getUiApplication().pushScreen(new ToplistScreen(_music, _player, Toplists.HOT));
			}
		});
        _toplistSet.add(_item);

        _item = new ListStyleButtonField("新歌榜");
        _item.setChangeListener(new FieldChangeListener()
        {
			public void fieldChanged(Field field, int context)
			{
				UiApplication.getUiApplication().pushScreen(new ToplistScreen(_music, _player, Toplists.NEW));
			}
		});
        _toplistSet.add(_item);

        //_item = new ListStyleButtonField("iTunes榜");
        //_toplistSet.add(_item);
        //_item = new ListStyleButtonField("Channel[V]华语榜");
        //_toplistSet.add(_item);

        _item = new ListStyleButtonField("最新专辑");
        _item.setChangeListener(new FieldChangeListener()
        {
			public void fieldChanged(Field field, int context)
			{
				UiApplication.getUiApplication().pushScreen(new NewAlbumScreen(_music));
			}
		});
        //_listSet.add(_item);

        //_item = new ListStyleButtonField("热门歌手");
        //_listSet.add(_item);

        //_item = new ListStyleButtonField("热门单曲");
        //_listSet.add(_item);

        //_item = new ListStyleButtonField("搜索");
        //_searchSet.add(_item);

        _foreground.add(_toplistSet);
        //_foreground.add(_listSet);
        //_foreground.add(_searchSet);
        add(_foreground);
    }

	private void searchSongs(final String keyword)
	{
		UiApplication.getUiApplication().invokeLater(new Runnable()
    	{
			public void run()
			{
				RefreshContentsScreen popupScreen = new RefreshContentsScreen(_music, keyword, RefreshActions.SONGSLIST);
				UiApplication.getUiApplication().pushModalScreen(popupScreen);

				SongsList songsList = popupScreen.getSongsList();

				if (popupScreen != null) {popupScreen = null;}
				if (songsList != null) {refreshSongsList(songsList);}
			}
		});
	}

	private void refreshSongsList(SongsList list)
	{
		Vector songsList = list.getSongsList();
		Song song;

		if (songsList.size() <= 0)
		{
			Function.errorDialog("No Result!");
			return;
		}

		if (_listSet.getManager() == null) {_foreground.add(_listSet);}
		if (_listSet.getFieldCount() > 0) {_listSet.deleteAll();}

		for (int i=0; i<songsList.size(); i++)
		{
			song = (Song) songsList.elementAt(i);
			if (song != null)
			{
				_item = new ListStyleButtonField(song);
				_item.setChangeListener(new FieldChangeListener()
				{
					public void fieldChanged(Field field, int context)
					{
						if (context != FieldChangeListener.PROGRAMMATIC) {getSongDetails();}
					}
				});
				_listSet.add(_item);
			}
		}
	}

	private void getSongDetails()
	{
		UiApplication.getUiApplication().invokeLater(new Runnable()
    	{
			public void run()
			{
				ListStyleButtonField item = (ListStyleButtonField) _listSet.getFieldWithFocus();
				RefreshContentsScreen popupScreen = new RefreshContentsScreen(_music, String.valueOf(item.getSongId()), RefreshActions.SONGDETAILS);
				UiApplication.getUiApplication().pushModalScreen(popupScreen);

				final SongDetails songDetails = popupScreen.getSongDetail();

				if (popupScreen != null) {popupScreen = null;}
				if (songDetails != null)
				{
					UiApplication.getUiApplication().invokeLater(new Runnable()
					{
						//public void run() {Function.errorDialog(songDetails.getDfsId_M() + "\n\n" + Digest.getEncryptedId(songDetails.getDfsId_M()) + "\n\n" + songDetails.getMp3Url());}//playMp3(songDetails.getMp3Url());}
						public void run() {_player.play(songDetails.getMp3Url());}
					});
				}
			}
		});
	}

	protected boolean keyChar(char key, int status, int time)
    {
		if (getFieldWithFocus() instanceof ForegroundManager)
		{
			switch (key)
			{
    			case Characters.SPACE:
    				_player.pause();
    				return true;
    			case Characters.LATIN_CAPITAL_LETTER_L:
    			case Characters.LATIN_SMALL_LETTER_L:
    				//if (_player != null)
    				//{
    				//	Function.errorDialog("Set song loop indefinitely!");
    				//	_player.setLoopCount(-1);
    				//}
    				return true;
    			case Characters.LATIN_CAPITAL_LETTER_R:
    			case Characters.LATIN_SMALL_LETTER_R:
    				//refreshStories();
    				return true;
    			case Characters.LATIN_CAPITAL_LETTER_Q:
    			case Characters.LATIN_SMALL_LETTER_Q:
    				//showExitDialog();
    				return true;
			}
		}

    	return super.keyChar(key, status, time);
    }

	protected boolean onSavePrompt() {return true;}

	public boolean onClose()
	{
		_player.close();
		_player = null;

		return super.onClose();
	}
}